<?php
/**
* @package system plugin Frontend-User-Access (plugin for component Frontend-User-Access)
* @version 3.0.4
* @copyright Copyright (C) 2008 Carsten Engel. All rights reserved.
* @license GPL
* @author http://www.pages-and-items.com
* @joomla Joomla is Free Software
*/

// no direct access
defined( '_JEXEC' ) or die( 'Restricted access' );

jimport( 'joomla.plugin.plugin' );

class plgSystemFrontenduseraccess extends JPlugin{

	var $database;
	var $fua_config;
	var $user_id;
	var $user_type;
	
	function plgSystemFrontenduseraccess(& $subject, $config){
		parent::__construct($subject, $config);
		$this->database = JFactory::getDBO();
		
		//get config		
		$this->fua_config = $this->get_config();
		
		//get user id
		$user =& JFactory::getUser();		
		$this->user_id = $user->get('id');
		$this->user_type = $user->get('usertype');
	}
	
	function get_config(){	
			
		$database = JFactory::getDBO();			
		
		$database->setQuery("SELECT config "
		."FROM #__fua_config "
		."WHERE id='fua' "
		."LIMIT 1"
		);		
		$raw = $database->loadResult();		
		
		$params = explode( "\n", $raw);
		
		for($n = 0; $n < count($params); $n++){		
			$temp = explode('=',$params[$n]);
			$var = $temp[0];
			$value = '';
			if(count($temp)==2){
				$value = trim($temp[1]);
				if($value=='false'){
					$value = false;
				}
				if($value=='true'){
					$value = true;
				}
			}							
			$config[$var] = $value;	
		}	
		
		//reformat redirect urls		
		$config['no_item_access_full_url'] = str_replace('[equal]','=',$config['no_item_access_full_url']);	
		$config['no_category_access_url'] = str_replace('[equal]','=',$config['no_category_access_url']);
		$config['no_section_access_url'] = str_replace('[equal]','=',$config['no_section_access_url']);	
		$config['no_component_access_url'] = str_replace('[equal]','=',$config['no_component_access_url']);	
		$config['no_menu_access_url'] = str_replace('[equal]','=',$config['no_menu_access_url']);					
				
		return $config;			
	}

	function work_on_buffer(){
	
		if(!strpos($_SERVER['REQUEST_URI'], 'administrator')){
		//only do stuff at the frontend
			
			//get buffer
			$buffer = JResponse::getBody();	
			
			if($this->user_type!='Super Administrator'){
				//check if any article needs hiding
				$pos = 0;
				$pos = strpos($buffer, '<br class="fua_article_hide"');
				if($pos){	
					//some articles need hiding
					$regex = "/frontend_user_access_article_hide_start(.*?)frontend_user_access_hide_article_end/is";
					preg_match_all($regex, $buffer, $matches); 		
					
					for($n = 0; $n < count($matches[0]); $n++){			
						if(strpos($matches[0][$n],'class="fua_article_hide"')){				
							//check trial version						
							if(file_exists(dirname(__FILE__).'/../../administrator/components/com_frontenduseraccess/controller.php')){			
								require_once(dirname(__FILE__).'/../../administrator/components/com_frontenduseraccess/controller.php');
								$controller = new frontenduseraccessController;
								if($controller->fua_check_trial_version()){
									//hide the actual article
									$buffer = str_replace($matches[0][$n],'',$buffer);
								}
							}				
						}
					}		
				}
			}
			
			//take out all temp-texts
			$buffer = str_replace('frontend_user_access_article_hide_start','',$buffer);
			$buffer = str_replace('frontend_user_access_hide_article_end','',$buffer);			
			
			//check for component access
			if($this->fua_config['use_componentaccess'] && $this->user_type!='Super Administrator'){	
					
				//get usergroup					
				$fua_usergroup = $this->get_usergroup_from_database();	
				
				$option = JRequest::getVar('option', '');
				
				//get component access data
				$this->database->setQuery("SELECT component_groupid FROM #__fua_components");
				$fua_component_access_rights = $this->database->loadResultArray();	
				
				$fua_component_right = $option.'__'.$fua_usergroup;				
				
				$fua_component_access = true;
				
				//check component permisson					
				if($this->fua_config['component_reverse_access']){
					if(in_array($fua_component_right, $fua_component_access_rights) && $option!='com_frontenduseraccess'){	
						$fua_component_access = false;									
					}
				}else{
					if(!in_array($fua_component_right, $fua_component_access_rights) && $option!='com_frontenduseraccess'){	
						$fua_component_access = false;									
					}
				}
				
				//if user has no component-access-permission
				if(!$fua_component_access){
					if($this->fua_config['components_message_type']=='alert'){	
						$message = addslashes($this->fua_config['message_no_component_access']);
						$this->do_alert($message);	
					}elseif($this->fua_config['components_message_type']=='redirect'){
						$live_site = JURI::root();	
						$url = $live_site.$this->fua_config['no_component_access_url'];
						global $mainframe;
						$mainframe->redirect($url);	
					}else{
						//get menu-item and live site							
						$menu_item = JRequest::getVar('Itemid', '');	
						$live_site = JURI::root();							
												
						$url = $live_site.'/index.php?option=com_frontenduseraccess&view=noaccess&Itemid='.$menu_item.'&type=4';
						if($this->fua_config['components_message_type']=='only_text'){
							$url .= '&tmpl=component';
						}	
						global $mainframe;
						$mainframe->redirect($url);						
					}
				}				
			}
			
			//check for module access
			if($this->fua_config['modules_active'] && file_exists(dirname(__FILE__).'/../../components/com_frontenduseraccess/simple_html_dom.php') && $this->user_type!='Super Administrator'){				
				
				//get module access rights
				$this->database->setQuery("SELECT module_groupid FROM #__fua_modules_two");
				$modules_access_array = $this->database->loadResultArray();	
				
				$regex = "/frontend_user_access_module_hide_(.*?)_/is";			
				preg_match_all($regex, $buffer, $matches); 				
				
				$module_ids = array_unique($matches[1]);
								
				//get usergroup
				$fua_usergroup = $this->get_usergroup_from_database();
				
				require_once(dirname(__FILE__).'/../../components/com_frontenduseraccess/simple_html_dom.php');				
				$html_fua = new simple_html_dom();				
				$html_fua->load($buffer);
				
				foreach($module_ids as $module_id){
					$module_right = $module_id.'__'.$fua_usergroup;
					
					$has_access_module = 1;	
					
					if($this->fua_config['modules_reverse_access']){
						if(in_array($module_right, $modules_access_array)){
							$has_access_module = 0;					
						}
					}else{
						if(!in_array($module_right, $modules_access_array)){
							$has_access_module = 0;		
						}
					}
					$element = $html_fua->find('[class=frontend_user_access_module_hide_'.$module_id.'_]', 0);
					if(!$has_access_module){						
						$element->outertext = ''; 															
					}					
					$class_names = $element->class;					
					$class_names = str_replace(' frontend_user_access_module_hide_'.$module_id.'_','',$class_names);					
					$element->class = $class_names;
				}
				
				//workaround for Docman
				if(JRequest::getVar('option', '')=='com_docman' && JRequest::getVar('task', '')=='upload' && (JRequest::getVar('step', '')==2 || JRequest::getVar('step', '')==3)){
					//on docman upload page								
					if(!$this->fua_config['docman_workaround']){
						//only do buffer thing if the workaround is disabled									
						$buffer = $html_fua->save();
					}
				}else{	
					//in all other cases, do the buffer thing					
					$buffer = $html_fua->save();
				}
			
			}	
			
			//write buffer
			JResponse::setBody($buffer);			
		}		 
	}
	
	function fua_check_page_access(){
	
		if(!strpos($_SERVER['REQUEST_URI'], 'administrator')){
			//only do this at the frontend
			
			static $page_access_checked;
			
			if(!$page_access_checked){
				global $mainframe;
				$menu_id = JRequest::getVar('Itemid', '');
				
				if($menu_id && $this->fua_config['use_menuaccess'] && $this->user_type!='Super Administrator'){		
					//echo 'sfrdvs';						
					
					//get usergroup
					$fua_usergroup = $this->get_usergroup_from_database();
					
					$menu_access_array = $this->get_menu_access_from_database();			
					
					$menu_right = $menu_id.'_'.$fua_usergroup;								
					
					$fua_menu_access = true;
					if($this->fua_config['menu_reverse_access']){
						if(in_array($menu_right, $menu_access_array)){
							$fua_menu_access = false;
						}
					}else{
						if(!in_array($menu_right, $menu_access_array)){
							$fua_menu_access = false;	
						}
					}	
					
					//if no access
					if(!$fua_menu_access){						
						if($this->fua_config['menuaccess_message_type']=='alert'){	
							$message = addslashes($this->fua_config['message_no_menu_access']);
							$this->do_alert($message);	
						}elseif($this->fua_config['menuaccess_message_type']=='inline_text'){				
							$url = JURI::root().'index.php?option=com_frontenduseraccess&view=noaccess&type=5';								
							$mainframe->redirect($url);			
						}elseif($this->fua_config['menuaccess_message_type']=='only_text'){											
							$url = JURI::root().'index.php?option=com_frontenduseraccess&view=noaccess&tmpl=component&type=5';								
							$mainframe->redirect($url);		
						}elseif($this->fua_config['menuaccess_message_type']=='redirect'){											
							$url = JURI::root().$this->fua_config['no_menu_access_url'];								
							$mainframe->redirect($url);		
						}
					}
				
				}
				$page_access_checked = 1;
			}
		}
	}
	
	//function bot_frontend_user_access_page( &$row, &$params, $page=0 ){
	function bot_frontend_user_access_page(){
		global $mainframe;
		static $bot_comp_and_url_done;
		
		if(!$bot_comp_and_url_done){
		
			//make sure page is not cached
			header("Cache-Control: no-cache, must-revalidate"); // HTTP/1.1
			header("Expires: Sat, 26 Jul 1997 05:00:00 GMT"); // Date in the past
			
			//get vars							
			$option = JRequest::getVar('option', '');
			$view = JRequest::getVar('view', '');	
			$layout = JRequest::getVar('layout', '');
			$item_id_temp = JRequest::getVar('id', '');	
			if(strpos($item_id_temp, ':')){
				$pos_item_id = strpos($item_id_temp, ':');
				$item_id = intval(substr($item_id_temp, 0, $pos_item_id));	
			}else{
				$item_id = intval($item_id_temp);	
			}	
				
			//start checking item full view access		
			if($option=='com_content' &&
			($view=='article' && ($layout=='default' || $layout=='')) &&
			($this->fua_config['items_active'] || $this->fua_config['categories_active'] || $this->fua_config['sections_active']) &&
			($this->user_type!='Super Administrator') 
			){				
					
				//get usergroup					
				$fua_usergroup = $this->get_usergroup_from_database();													
				
				$fua_full_item_access = true;
				$type = '';
				$type_name = '';
				
				//check item access
				if($this->fua_config['items_active']){
				
					$item_access_array = $this->get_item_access_from_database();	
			
					$item_right = $item_id.'__'.$fua_usergroup;								
					
					if($this->fua_config['items_reverse_access']){
						if(in_array($item_right, $item_access_array)){
							$fua_full_item_access = false;
							$type = 1;
							$type_name = 'items';
						}
					}else{
						if(!in_array($item_right, $item_access_array)){
							$fua_full_item_access = false;
							$type = 1;
							$type_name = 'items';	
						}
					}							
				}//end item access
				
			
				
				//check category access
				if($this->fua_config['categories_active']){
				
					$category_access_array = $this->get_category_access_from_database();	
												
					//get category id of item
					$this->database->setQuery("SELECT catid "
					."FROM #__content "
					."WHERE id='$item_id' "
					."LIMIT 1 "
					);
					$fua_category_rows = $this->database->loadObjectList();
					$category_id = '';
					foreach($fua_category_rows as $fua_category_row){	
						$category_id = $fua_category_row->catid;	
					}
			
					$category_right = $category_id.'__'.$fua_usergroup;	
							
					if($this->fua_config['category_reverse_access']){
						if(in_array($category_right, $category_access_array)){
							$fua_full_item_access = false;
							$type = 2;
							$type_name = 'category';
						}
					}else{
						if(!in_array($category_right, $category_access_array)){
							$fua_full_item_access = false;	
							$type = 2;
							$type_name = 'category';
						}
					}
										
				}//end category access	
				
				//check section access
				if($this->fua_config['sections_active']){
				
					$section_access_array = $this->get_section_access_from_database();	
												
					//get section id of item
					$this->database->setQuery("SELECT sectionid "
					."FROM #__content "
					."WHERE id='$item_id' "
					."LIMIT 1 "
					);
					$fua_section_rows = $this->database->loadObjectList();
					$section_id = '';
					foreach($fua_section_rows as $fua_section_row){	
						$section_id = $fua_section_row->sectionid;	
					}
			
					$section_right = $section_id.'__'.$fua_usergroup;	
							
					if($this->fua_config['sections_reverse_access']){
						if(in_array($section_right, $section_access_array)){
							$fua_full_item_access = false;
							$type = 3;
							$type_name = 'section';
						}
					}else{
						if(!in_array($section_right, $section_access_array)){
							$fua_full_item_access = false;	
							$type = 3;
							$type_name = 'section';
						}
					}
										
				}//end section access					
				
				$type_message_type = $type_name.'_message_type';
				
				//if no access
				if(!$fua_full_item_access){								
					if($this->fua_config[$type_message_type]=='alert'){							
						$message = addslashes($this->fua_config['message_no_item_access_full']);
						$this->do_alert($message);
					}elseif($this->fua_config[$type_message_type]=='redirect'){
						$live_site = JURI::root();
						if($type_name=='items'){
							$url2 = $this->fua_config['no_item_access_full_url'];
						}elseif($type_name=='category'){
							$url2 = $this->fua_config['no_category_access_url'];
						}elseif($type_name=='section'){
							$url2 = $this->fua_config['no_section_access_url'];
						}
						$url = $live_site.$url2;
						$mainframe->redirect($url);	
					}else{								
						//get menu-item	
						$menu_item = JRequest::getVar('Itemid', '');
						$live_site = JURI::root();										
						$url = $live_site.'index.php?option=com_frontenduseraccess&view=noaccess&Itemid='.$menu_item.'&type='.$type;
						if($this->fua_config[$type_message_type]=='only_text'){
							$url .= '&tmpl=component';
						}										
						$mainframe->redirect($url);									
					}
				}						
									
					
			}//end if anything needs checking
			$bot_comp_and_url_done = 1;
		}//end if only do this once
	}	
	
	function get_item_access_from_database(){
	
		static $item_access_array;
		
		if(!$item_access_array){	
			
			$this->database->setQuery("SELECT itemid_groupid FROM #__fua_items ");
			$item_access_array = $this->database->loadResultArray();	
			
		}
		
		return $item_access_array;
	}
	
	function get_category_access_from_database(){
	
		static $category_access_array;
		
		if(!$category_access_array){	
			
			$this->database->setQuery("SELECT category_groupid FROM #__fua_categories ");
			$category_access_array = $this->database->loadResultArray();	
			
		}
		
		return $category_access_array;
	}
	
	function get_section_access_from_database(){
	
		static $section_access_array;
		
		if(!$section_access_array){	
			
			$this->database->setQuery("SELECT section_groupid FROM #__fua_sections ");
			$section_access_array = $this->database->loadResultArray();	
			
		}
		
		return $section_access_array;
	}
	
	function get_menu_access_from_database(){
	
		static $menu_access_array;
		
		if(!$menu_access_array){	
			
			$this->database->setQuery("SELECT menuid_groupid FROM #__fua_menuaccess ");
			$menu_access_array = $this->database->loadResultArray();	
			
		}
		
		return $menu_access_array;
	}	
	
	function get_usergroup_from_database(){
	
		static $fua_usergroup;
		
		if(!$fua_usergroup){
		
			if(!$this->user_id){
				//user is not logged in
				$fua_usergroup = '10';
			}else{
				$user_id = $this->user_id;
				$this->database->setQuery("SELECT group_id FROM #__fua_userindex WHERE user_id='$user_id' LIMIT 1 ");		
				$rows_group = $this->database->loadObjectList();	
				$fua_usergroup = false;		
				foreach($rows_group as $row_group){
					$fua_usergroup = $row_group->group_id;	
				}
				
				if(!$fua_usergroup){
					//user is logged in, but is not assigned to any usergroup, so make it 9
					$fua_usergroup = '9';
				}
			}	
		}	
		return $fua_usergroup;
	}
	
	function do_alert($message){		
		echo '<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />';
		echo "<script>alert('".html_entity_decode($message)."'); window.history.go(-1); </script>";
		exit('<html><body><noscript>'.$message.'</noscript></body></html>');
	}
	
	function onAfterRender(){
		$this->work_on_buffer();
		$this->fua_check_page_access();
	}
	
	function onBeforeDisplayContent(){
		$this->bot_frontend_user_access_page();		
	}
}

?>